"""
Copyright © 2021 Walkline Wang (https://walkline.wang)
Gitee: https://gitee.com/walkline/spaceman
"""
import os
from machine import I2C, Pin
from ssd1306 import SSD1306_I2C
import framebuf


class SpaceMan(object):
	IMAGE_ROOT = 'images/pbm/'
	IMAGE_EXTENSION = '.pbm'

	def __init__(self):
		self.__images = self.__images_generator()

	def next_framebuffer(self):
		buffer = None
		image_filename = next(self.__images)

		with open(image_filename, 'rb') as pbm_file:
			pbm_file.readline() # 忽略 pbm 文件首行内容

			# 从文件第二行获取图片长宽
			size = pbm_file.readline().replace(b'\n', b'').split(b' ')
			pbm_width = int(size[0])
			pbm_height = int(size[1])

			# 文件其余内容为图像数据
			buffer = pbm_file.read()

		return framebuf.FrameBuffer(
			bytearray(memoryview(buffer)),
			pbm_width,
			pbm_height,
			framebuf.MONO_HLSB) if buffer else None

	def __images_generator(self):
		try:
			images_list = os.listdir(self.IMAGE_ROOT)
			images_list = [image for image in images_list if image.endswith(self.IMAGE_EXTENSION)]

			index = 0
			count = len(images_list)

			if count == 0:
				raise Exception('no pbm file found')

			while True:
				yield f'{self.IMAGE_ROOT}{images_list[index]}'
				index = (index + 1) % count
		except OSError as ose:
			if str(ose) == '[Errno 2] ENOENT':
				raise Exception('upload image files to images/pbm/ first.')


i2c = None
oled = None

def initialize():
	global i2c, oled

	i2c = I2C(0, scl=Pin(18), sda=Pin(19))
	slave_list = i2c.scan()

	if slave_list:
		print(f'found i2c device, id: {slave_list[0]}')
		oled = SSD1306_I2C(128, 64, i2c)

	return slave_list


# 调试时只显示第一张图片
debug = False

if __name__ == '__main__':
	if initialize():
		spaceman = SpaceMan()

		while True:
			buffer = spaceman.next_framebuffer()

			if buffer:
				oled.blit(buffer, 0, 0)
				oled.show()

			if debug:
				break
	else:
		print('no i2c device found')
